package cn.yunhe.controller;


import cn.yunhe.model.*;
import cn.yunhe.service.IBuyInsurService;
import cn.yunhe.service.ILoginService;
import cn.yunhe.service.IRoleService;
import cn.yunhe.utils.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Author :  Amayadream
 * Date   :  2016.01.08 14:57
 * TODO   :  用户登录与注销
 */
@Controller
@RequestMapping(value = "/user")
@SessionAttributes("msg")
public class LoginController {

    @Resource(name="loginServiceImpl")
    private ILoginService userService;

    /*购买保险*/
    @Resource
    private IBuyInsurService buyInsurService;
    @Resource
    private IRoleService roleService;

    private static int flag = 0;//短信验证标志位
    private static String phone = "";//短信验证手机号


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "redirect:/login.jsp";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(String userid, String password,String duanxin, HttpSession session,WordDefined defined) {

        ModelAndView mv = new ModelAndView();
        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg("进行用户登录操作");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("登录");//(添加，删除，修改)
        blog.setUn_id(1);//session中的当前用户id
        ma.put("blog",blog);
        UserNumber users = new UserNumber ();
        users.setUsername(userid);
        ma.put("users",users);

        //ByteSource
        ByteSource salt = ByteSource.Util.bytes(userid);
        //将密码加密
        SimpleHash sh = new SimpleHash("MD5",password,salt,1024);
        System.out.println(sh);
        password = sh.toString();

        UserNumber user = userService.LoginUserByUserid(ma);//用户所有信息
        if (flag>=3){
        if (session.getAttribute("msg")==null){
            session.setAttribute("error","请获取验证码");
            System.out.println("请获取验证码");
            mv.setViewName("redirect:/login.jsp");
            return mv;
        }else{
            //连续三次密码不正确进行短信验证
            System.out.println(session.getAttribute("msg")+"==="+duanxin);

                if(!session.getAttribute("msg").equals(duanxin)){
                    session.setAttribute("error","验证码错误");
                    System.out.println("验证码错误");
                    mv.setViewName("redirect:/login.jsp");
                    return mv;
                }
            }
        }

        System.out.println("+++++"+userid+"+++"+password);
        if (user == null) {
            session.setAttribute("error",defined.LOGIN_USERID_ERROR);
            System.out.println(defined.LOGIN_USERID_ERROR);
            mv.setViewName("redirect:/login.jsp");
            return mv;
        } else {
            if (!user.getPassword().equals(password)) {
                session.setAttribute("error", defined.LOGIN_PASSWORD_ERROR);
                flag++;//密码不正确次数记录
                phone=user.getUn_pwdsalt();
                session.setAttribute("loginflag", flag);
                System.out.println(defined.LOGIN_PASSWORD_ERROR+"===="+flag);
                mv.setViewName("redirect:/login.jsp");
                return mv;
            } else {
                if (user.getUn_state() == 0) {
                    session.setAttribute("error",defined.LOGIN_USERID_DISABLED);
                    System.out.println(defined.LOGIN_USERID_DISABLED);
                    mv.setViewName("redirect:/login.jsp");
                    return mv;
                } else {
                   // logService.insert(logUtil.setLog(userid, date.getTime24(), defined.LOG_TYPE_LOGIN, defined.LOG_DETAIL_USER_LOGIN, netUtil.getIpAddress(request)));
                    Member member = new Member();
                    if(user.getUsers()!=null)
                     member = buyInsurService.queryUsermember(user.getUsers().getU_jifen());//用户会员信息
                    /*Power power = userService.queryquanxian(user.getRole().getP_id());//用户权限信息*/
                    System.out.println(member.getM_name());
                    session.setAttribute("userid", userid);//聊天室专用
                    session.setAttribute("login_status", true);//聊天室专用

                    //ByteSource
                    ByteSource salt1 = ByteSource.Util.bytes(user.getUsername());
                    //将密码加密
                    SimpleHash sh1 = new SimpleHash("MD5",user.getUsername(),salt,1024);
                    System.out.println(sh1+user.getPassword());
                    String password1 = sh1.toString();
                    session.setAttribute("bijiaomima",password1);
                    session.setAttribute("UsernumberRoleUsers",user);//用户的主要信息，包含账号用户角色等一些主要信息
                    session.setAttribute("UsersMember",member);//主要包含会员的等级以及会员的保险优惠率
                    /*session.setAttribute("UsersPower",power);//用于做会员的权限*/
                    //将所有权限存以列表的形式存入session
                    List<String> roles = new ArrayList<String>();
                    Role role = roleService.queryRoleById(user.getRole());
                    String powers = role.getPowers();
                    session.setAttribute("role",role );
                    session.setAttribute("UsersPower",powers );
                    mv.addObject("message", defined.LOGIN_SUCCESS);

                    blog.setLog_busimasg(session.getAttribute("userid")+"用户登录成功");//简单的业务描述
                    blog.setLog_addtime(new Date());
                    blog.setLog_busitype("登录");//(添加，删除，修改)
                    blog.setUn_id(user.getUn_id());//session中的当前用户id
                    ma.put("blog",blog);
                    userService.Loginuser(ma);
                    flag = 0;//把短信验证标志位清零
                    session.removeAttribute("loginflag");


                    //1.创建subject实例
                    Subject currentUser = SecurityUtils.getSubject();
                    //2.判断当前用户是否登录
                    if(!currentUser.isAuthenticated()){
                        //将用户名密码封装UsernamePasswordToken
                        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
                        try {
                            currentUser.login(token);
                        } catch ( AuthenticationException ae ) {
                            ae.printStackTrace();
                            //认证异常
                            //无法判断的情形
                            mv.setViewName("redirect:/login.jsp");
                            return mv;
                        }
                    }
                    mv.setViewName("redirect:/index/toindex.do");
                    return mv;
                }
            }
        }
    }

    /**
     * 发送验证码
     * user 根据用户的信息返回手机号，并发送验证码。
     */
    @RequestMapping("/captcha")
    public ModelAndView Captcha(@RequestParam(value="user" ,required =false )UserNumber user, HttpSession session) {

        //已经查询回来手机号码了。
        String msg = RandomStringUtil.getRandomCode(6,0);
        String smsContent = "【安康保险】尊敬的用户，您的验证码为"+msg;
        IndustrySMS.execute(phone,smsContent);
        ModelAndView mv = new ModelAndView();
        session.setAttribute("msg",msg);
        mv.addObject("flag",1);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session, RedirectAttributes attributes, WordDefined defined) {

        Map<String,Object> ma = new HashMap<String, Object>();
        Busilog blog=new Busilog();//日志信息的描述
        blog.setLog_busimasg(session.getAttribute("userid")+"进行用户注销操作");//简单的业务描述
        blog.setLog_addtime(new Date());
        blog.setLog_busitype("注销");//(添加，删除，修改)
        blog.setUn_id(1);//session中的当前用户id
        ma.put("blog",blog);
        userService.Zhuxiaouser(ma);
        session.removeAttribute("userid");
        session.removeAttribute("login_status");
        session.invalidate();

        attributes.addFlashAttribute("message", defined.LOGOUT_SUCCESS);
        return "redirect:/login.jsp";
    }
}
